import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import calculator
import db

print("请不要关闭此窗口，否则程序将退出！")

class App:
    def __init__(self):
        calculator.FeeCalculator.log_action("启动程序，创建主窗口")
        self.root = tk.Tk()
        # 设置窗口背景颜色
        self.root.configure(bg='#F0F0F0')
        # 设置窗口图标
        try:
            self.root.iconbitmap('app.ico')
        except:
            pass
        #messagebox.showinfo("提示", "请不要关闭命令行窗口，否则程序将退出！", parent=self.root)
        self.root.title('评估费计算器')
        self.root.wm_attributes('-topmost', 1)
        # 设置窗口大小
        self.root.geometry('800x600')

        self.notebook = ttk.Notebook(self.root, style='TNotebook')
        # 设置Notebook样式
        style = ttk.Style()
        style.theme_use('clam')
        style.configure('TNotebook', background='#F0F0F0')
        style.configure('TNotebook.Tab', background='#E0E0E0', foreground='black', font=('Arial', 12))
        style.map('TNotebook.Tab', background=[('selected', '#FFFFFF')])

        # 创建三个计算器标签页
        calculator.FeeCalculator.log_action("开始创建房产评估标签页")
        self.create_real_estate_tab()
        calculator.FeeCalculator.log_action("开始创建土地评估标签页")
        self.create_land_tab()
        calculator.FeeCalculator.log_action("开始创建资产评估标签页")
        self.create_asset_tab()

        self.notebook.pack(expand=1, fill='both', padx=20, pady=20)
        calculator.FeeCalculator.log_action("开始创建历史记录视图")
        self.create_history_view()

    def create_real_estate_tab(self):
        frame = ttk.Frame(self.notebook, style='TFrame')
        # 设置标签字体和颜色
        ttk.Label(frame, text='评估金额（万元）', font=('Arial', 12), style='TLabel').grid(row=0, column=0, padx=10, pady=10, sticky='w')
        self.real_estate_entry = ttk.Entry(frame, font=('Arial', 12))
        self.real_estate_entry.grid(row=0, column=1, padx=10, pady=10, sticky='ew')

        self.result_label_real = tk.Label(frame, text='评估费：0.0000 万元', foreground='#FF4500', font=('Arial', 14, 'bold'))
        self.result_label_real.grid(row=1, column=0, columnspan=2, pady=10)

        ttk.Label(frame, text='折扣率', font=('Arial', 12), style='TLabel').grid(row=2, column=0, padx=10, pady=10, sticky='w')
        self.discount_entry_real = ttk.Entry(frame, font=('Arial', 12))
        self.discount_entry_real.grid(row=2, column=1, padx=10, pady=10, sticky='ew')

        self.discounted_result_label_real = tk.Label(frame, text='折后评估费：0.0000 万元', foreground='#FF6347', font=('Arial', 14, 'bold'))
        self.discounted_result_label_real.grid(row=3, column=0, columnspan=2, pady=10)
        self.real_estate_entry.bind('<KeyRelease>', lambda e: self.calculate('房产', self.real_estate_entry, self.discount_entry_real))
        self.discount_entry_real.bind('<KeyRelease>', lambda e: self.calculate('房产', self.real_estate_entry, self.discount_entry_real))
        self.notebook.add(frame, text='房产评估')
        calculator.FeeCalculator.log_action("完成创建房产评估标签页")

    def create_land_tab(self):
        frame = ttk.Frame(self.notebook, style='TFrame')
        ttk.Label(frame, text='评估金额（万元）', font=('Arial', 12), style='TLabel').grid(row=0, column=0, padx=10, pady=10, sticky='w')
        self.land_entry = ttk.Entry(frame, font=('Arial', 12))
        self.land_entry.grid(row=0, column=1, padx=10, pady=10, sticky='ew')

        self.result_label_land = tk.Label(frame, text='评估费：0.0000 万元', foreground='#FF4500', font=('Arial', 14, 'bold'))
        self.result_label_land.grid(row=1, column=0, columnspan=2, pady=10)

        ttk.Label(frame, text='折扣率', font=('Arial', 12), style='TLabel').grid(row=2, column=0, padx=10, pady=10, sticky='w')
        self.discount_entry_land = ttk.Entry(frame, font=('Arial', 12))
        self.discount_entry_land.grid(row=2, column=1, padx=10, pady=10, sticky='ew')

        self.discounted_result_label_land = tk.Label(frame, text='折后评估费：0.0000 万元', foreground='#FF6347', font=('Arial', 14, 'bold'))
        self.discounted_result_label_land.grid(row=3, column=0, columnspan=2, pady=10)
        self.land_entry.bind('<KeyRelease>', lambda e: self.calculate('土地', self.land_entry, self.discount_entry_land))
        self.discount_entry_land.bind('<KeyRelease>', lambda e: self.calculate('土地', self.land_entry, self.discount_entry_land))
        self.notebook.add(frame, text='土地评估')
        calculator.FeeCalculator.log_action("完成创建土地评估标签页")

    def create_asset_tab(self):
        frame = ttk.Frame(self.notebook, style='TFrame')
        ttk.Label(frame, text='评估金额（万元）', font=('Arial', 12), style='TLabel').grid(row=0, column=0, padx=10, pady=10, sticky='w')
        self.asset_entry = ttk.Entry(frame, font=('Arial', 12))
        self.asset_entry.grid(row=0, column=1, padx=10, pady=10, sticky='ew')

        self.result_label_asset = tk.Label(frame, text='评估费：0.0000 万元', foreground='#FF4500', font=('Arial', 14, 'bold'))
        self.result_label_asset.grid(row=1, column=0, columnspan=2, pady=10)

        ttk.Label(frame, text='折扣率', font=('Arial', 12), style='TLabel').grid(row=2, column=0, padx=10, pady=10, sticky='w')
        self.discount_entry_asset = ttk.Entry(frame, font=('Arial', 12))
        self.discount_entry_asset.grid(row=2, column=1, padx=10, pady=10, sticky='ew')

        self.discounted_result_label_asset = tk.Label(frame, text='折后评估费：0.0000 万元', foreground='#FF6347', font=('Arial', 14, 'bold'))
        self.discounted_result_label_asset.grid(row=3, column=0, columnspan=2, pady=10)
        self.asset_entry.bind('<KeyRelease>', lambda e: self.calculate('资产', self.asset_entry, self.discount_entry_asset))
        self.discount_entry_asset.bind('<KeyRelease>', lambda e: self.calculate('资产', self.asset_entry, self.discount_entry_asset))
        self.notebook.add(frame, text='资产评估')
        calculator.FeeCalculator.log_action("完成创建资产评估标签页")

    def calculate(self, calc_type, entry_widget, discount_widget):
        calculator.FeeCalculator.log_action(f"开始 {calc_type} 评估计算")
        try:
            amount = float(entry_widget.get())
            result = round(calculator.FeeCalculator.calculate(amount, calc_type), 4)
            discount = discount_widget.get()
            original_result = result
            if discount:
                try:
                    discount_rate = float(discount)
                    result = round(result * discount_rate, 4)
                except ValueError:
                    pass

            if calc_type == '房产':
                self.result_label_real.config(text=f'评估费：{original_result:.4f} 万元')
                self.discounted_result_label_real.config(text=f'折后评估费：{result:.4f} 万元')
            elif calc_type == '土地':
                self.result_label_land.config(text=f'评估费：{original_result:.4f} 万元')
                self.discounted_result_label_land.config(text=f'折后评估费：{result:.4f} 万元')
            else:
                self.result_label_asset.config(text=f'评估费：{original_result:.4f} 万元')
                self.discounted_result_label_asset.config(text=f'折后评估费：{result:.4f} 万元')
            calculator.FeeCalculator.log_action(f"开始将 {calc_type} 计算记录添加到数据库")
            db.Database().add_record(calc_type, amount, original_result, discount if discount else '无', result)
            calculator.FeeCalculator.log_action("开始加载历史记录")
            self.load_history()
        except ValueError:
            pass
        finally:
            calculator.FeeCalculator.log_action("完成加载历史记录")
            calculator.FeeCalculator.log_action("完成重新加载历史记录")
            calculator.FeeCalculator.log_action("完成清空历史记录")
            calculator.FeeCalculator.log_action("完成创建历史记录视图")

    def create_history_view(self):
        calculator.FeeCalculator.log_action("开始创建历史记录视图界面")
        history_frame = ttk.Frame(self.root, style='TFrame')
        history_frame.pack(fill='both', expand=True, padx=20, pady=20)

        columns = ('类型', '金额', '评估费', '折扣率', '折后评估费', '时间')
        self.tree = ttk.Treeview(history_frame, columns=columns, show='headings', style='Treeview')
        for col in columns:
            self.tree.heading(col, text=col)
            self.tree.column(col, width=150 if col == '时间' else 80, stretch=True)

        scrollbar = ttk.Scrollbar(history_frame, orient='horizontal', command=self.tree.xview)
        scrollbar.pack(side='bottom', fill='x')
        self.tree.configure(xscrollcommand=scrollbar.set)
        self.tree.pack(fill='both', expand=True)

        # 添加删除按钮
        btn_frame = ttk.Frame(history_frame, style='TFrame')
        btn_frame.pack(pady=5)

        self.clear_btn = ttk.Button(btn_frame, text='清空历史记录', style='TButton', 
                                  command=lambda: [calculator.FeeCalculator.log_action("开始清空历史记录"), db.Database().delete_all_records(), calculator.FeeCalculator.log_action("开始重新加载历史记录"), self.load_history()])
        self.clear_btn.pack(side='right', padx=10)

        calculator.FeeCalculator.log_action("开始加载历史记录")
        self.load_history()
        calculator.FeeCalculator.log_action("完成创建历史记录视图")

    def load_history(self):
        calculator.FeeCalculator.log_action("开始清空历史记录视图")
        for item in self.tree.get_children():
            self.tree.delete(item)
        calculator.FeeCalculator.log_action("开始从数据库加载历史记录")
        for record in db.Database().get_history():
            formatted_record = (
                record[0],
                f'{record[1]:.4f}',
                f'{record[2]:.4f}',
                record[3],
                f'{record[4]:.4f}',
                record[5]
            )
            self.tree.insert('', 'end', values=record)
        calculator.FeeCalculator.log_action("完成从数据库加载历史记录")

if __name__ == '__main__':
    app = App()
    app.root.mainloop()